package com.luoxiang.socialandroid.app;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.faceunity.core.callback.OperateCallback;
import com.faceunity.core.faceunity.FURenderKit;
import com.faceunity.core.faceunity.FURenderManager;
import com.faceunity.core.utils.FULogger;
import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.utils.DensityUtil;
import com.luoxiang.lib_common.app.App;
import com.luoxiang.lib_common.common.Constants;
import com.luoxiang.lib_common.utils.authpack;
import com.luoxiang.socialandroid.BuildConfig;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.LoginbyCodeActivity;
import com.luoxiang.socialandroid.bean.Extra;
import com.luoxiang.socialandroid.bean.UMSystemMassageBean;
import com.luoxiang.socialandroid.bean.UMSystemMassageDataBean;
import com.luoxiang.socialandroid.dialog.LoginServiceTipDialog;
import com.luoxiang.socialandroid.dialog.PrivacyDialog;
import com.luoxiang.socialandroid.utils.DeviceUtils;
import com.luoxiang.socialandroid.utils.LogUtils;
import com.lxj.xpopup.XPopup;
import com.netease.lava.nertc.foreground.ForegroundKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.mixpush.MixPushConfig;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.netease.nis.quicklogin.QuickLogin;
import com.netease.nis.quicklogin.helper.UnifyUiConfig;
import com.netease.nis.quicklogin.listener.LoginListener;
import com.netease.nis.quicklogin.ui.CmccLoginActivity;
import com.netease.yunxin.kit.chatkit.ui.ChatKitClient;
import com.netease.yunxin.kit.corekit.im.IMKitClient;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mmkv.MMKV;
import com.umeng.commonsdk.UMConfigure;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import cn.net.shoot.sharetracesdk.ShareTrace;

/**
 * @Description TODO
 * @systemUser Administrator
 * @Author LiangXin
 * @Date 08-18-2022 周四 13:41
 */
public class MyAppliaction extends MultiDexApplication {
    //存放activity的集合
    public List<Activity> activities;
    //页面切换传递数据的集合
    private Map<String, Object> transmitDataMap;
    public static String PATH = "";
    private static Context context;
    public BDLocation bdLocation;
    private Activity quickLoginActivity;
    private boolean isCheck = false;
    public boolean whetherReceivePopovers = false;
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private Extra extra = new Gson().fromJson(Constants.MmkvConst.EXTRA, Extra.class);
    /**
     * 利用单例模式获取application
     */

    private static MyAppliaction appliaction = null;

    public static synchronized MyAppliaction getMyAppliaction() {
        return appliaction;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    static {//使用static代码段可以防止内存泄漏
        //全局设置默认的 Header
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //开始设置全局的基本参数（这里设置的属性只跟下面的MaterialHeader绑定，其他Header不会生效，能覆盖DefaultRefreshInitializer的属性和Xml设置的属性）
                layout.setEnableHeaderTranslationContent(false);
                return new ClassicsHeader(context);
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appliaction = this;
        App.application = this;
        ToastUtils.init(this);
        ToastUtils.setGravity(Gravity.CENTER);
        activities = new ArrayList<Activity>();
        transmitDataMap = new HashMap<String, Object>();
        //启动器进行异步初始化
        MMKV.initialize(this);
        //设置信任所有https请求
        handleSSLHandshake();
        initLogin();
        //相机日志 上线记得关闭 OFF
        FURenderManager.setKitDebug(FULogger.LogLevel.DEBUG);
        FURenderManager.setCoreDebug(FULogger.LogLevel.DEBUG);
        context = getApplicationContext();
        initUIKit();
        initUM();
        ShareTrace.init(this);
        initCramer();
        SDKInitializer.setAgreePrivacy(context, true);
        SDKInitializer.initialize(this);
        initExtra();
        initBaiduLocation();
        initForeground();
        CrashReport.initCrashReport(getApplicationContext(), "ddd4c77b69", false);


//        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//// 填写STS应用服务器地址。
//        String stsServer = "https://example.com";
//// 推荐使用OSSAuthCredentialsProvider。token过期可以及时更新。
//        OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(stsServer);
//
//// 配置类如果不设置，会有默认配置。
//        ClientConfiguration conf = new ClientConfiguration();
//        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
//        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。
//        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个。
//        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。
//
//        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);

    }

    private void initFacebook() {
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
    }

    private void initUM() {
        UMConfigure.preInit(
                context,
                "6363662b05844627b5784940",
                "Unknown"
        );
        UMConfigure.init(
                context,
                "6363662b05844627b5784940",
                "Unknown",
                UMConfigure.DEVICE_TYPE_PHONE,
                ""
        );
    }

    private void initForeground() {
        //正式f3cfe81e713709e6e61eb9a5dc65b51d
        if (ForegroundKit.getInstance(this).checkNotifySetting() && ForegroundKit.getInstance(this).checkFloatPermission()) {
            ForegroundKit.getInstance(this).init("f31308a092ca2a9afaa474af066c1935", 60 * 60 * 1000);
        }
    }

    public void startWhetherReceivePopovers() {
        whetherReceivePopovers = false;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                whetherReceivePopovers = true;
            }
        }, 5000);
    }

    private void initLogin() {
        QuickLogin quickLogin = QuickLogin.getInstance();
        View viewLoginCode = LayoutInflater.from(this).inflate(R.layout.view_login_code, null);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.topMargin = DensityUtil.dip2px(this, 490);
        viewLoginCode.setLayoutParams(lp);
        View viewLoginService = LayoutInflater.from(this).inflate(R.layout.view_login_service, null);
        LinearLayout.LayoutParams viewLoginServiceLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        viewLoginServiceLp.topMargin = DensityUtil.dip2px(this, 47);
        viewLoginService.setLayoutParams(viewLoginServiceLp);
        UnifyUiConfig unifyUiConfig = new UnifyUiConfig.Builder()
                .addCustomView(viewLoginCode, null, UnifyUiConfig.POSITION_IN_ROOT, (context, view) -> {
                    if (quickLoginActivity == null) {
                        return;
                    }
                    if (isCheck) {
                        Intent intent = new Intent(MyAppliaction.this, LoginbyCodeActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MyAppliaction.this.startActivity(intent);
                        return;
                    }
                    PrivacyDialog privacyDialog = new PrivacyDialog(quickLoginActivity);
                    privacyDialog.setOnConfirmClickListener(() -> {
                        quickLogin.setPrivacyState(true);
                        privacyDialog.dismiss();
                        Intent intent = new Intent(MyAppliaction.this, LoginbyCodeActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MyAppliaction.this.startActivity(intent);
                        return null;
                    });
                    privacyDialog.setOnCancleClickListener(() -> {
                        quickLogin.setPrivacyState(false);
                        privacyDialog.dismiss();
                        return null;
                    });
                    new XPopup.Builder(quickLoginActivity)
                            .asCustom(privacyDialog)
                            .show();
                })
                .addCustomView(viewLoginService, null, UnifyUiConfig.POSITION_IN_ROOT, (context, view) -> {
                    if (quickLoginActivity == null) {
                        return;
                    }
                    new XPopup.Builder(quickLoginActivity)
                            .asCustom(new LoginServiceTipDialog(quickLoginActivity))
                            .show();
                })
                .setProtocol2Text(getString(R.string.mi_yonghuxieyi))
                .setProtocol3Text(getString(R.string.mi_yinsizhengce))
                .setProtocol2Link("http://mlhtml-test.dhxwlkj.com/userAgreement/index.html")
                .setProtocol3Link("http://mlhtml-test.dhxwlkj.com/privacyPolicy/index.html")
                .setPrivacyState(false)
                .setCheckBoxGravity(Gravity.TOP)
                .setClickEventListener((i, i1) -> {
                    if (i == 4) {
                        //1：电信 2：移动 3：联通 4:wifi 5：未知
                        int type = quickLogin.checkNetWork(this);
                        //todo 弹出隐私政策框
                    }
                    if (i == 2) {
                        isCheck = i1 == 1;
                    }
                })
                .setBackgroundVideo("https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/data/video/bg_login.mp4", "bg_login")
                .setHideNavigation(true)
                .setStatusBarColor(R.color.transparent)
                .setLogoIconDrawable(ContextCompat.getDrawable(this, R.mipmap.bk_loginbk))
                .setLogoWidth(74)
                .setLogoHeight(74)
                .setLogoTopYOffset(140)
                .setSloganDpSize(13)
                .setSloganColor(Color.parseColor("#FFFFFF"))
                .setSloganTopYOffset(328)
                .setLoginBtnBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.shape_btnonelogin))
                .setLoginBtnText(getString(R.string.mi_benjihaomayijiandenglu))
                .setLoginBtnTextColor(Color.parseColor("#333333"))
                .setLoginBtnTextSize(18)
                .setLoginBtnWidth(321)
                .setLoginBtnTopYOffset(357)
                .setLoginBtnHeight(53)
                .setPrivacyTextColor(Color.parseColor("#999999"))
                .setPrivacyProtocolColor(Color.parseColor("#FFFFFF"))
                .setPrivacySize(12)
                .setPrivacyMarginLeft(50)
                .setPrivacyMarginRight(50)
                .setPrivacyBottomYOffset(64)
                .setPrivacyTextMarginLeft(12)
                .setCheckedImageDrawable(ContextCompat.getDrawable(this, R.mipmap.yijinggouxuan))
                .setUnCheckedImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_selectfalse))
                .setMaskNumberColor(Color.parseColor("#FFFFFF"))
                .setMaskNumberSize(28)
                .setMaskNumberTopYOffset(258)
                .setActivityTranslateAnimation(null, null)
                .setLoginListener(new LoginListener() {
                    @Override
                    public boolean onDisagreePrivacy(TextView privacyTv, Button btnLogin) {
                        PrivacyDialog privacyDialog = new PrivacyDialog(btnLogin.getContext());
                        privacyDialog.setOnConfirmClickListener(() -> {
                            quickLogin.setPrivacyState(true);
                            isCheck = true;
                            privacyDialog.dismiss();
                            return null;
                        });
                        privacyDialog.setOnCancleClickListener(() -> {
                            quickLogin.setPrivacyState(false);
                            isCheck = false;
                            privacyDialog.dismiss();
                            return null;
                        });
                        new XPopup.Builder(btnLogin.getContext())
                                .asCustom(privacyDialog)
                                .show();
                        return true;
                    }
                })
                .setActivityLifecycleCallbacks(new com.netease.nis.quicklogin.listener.ActivityLifecycleCallbacks() {
                    @Override
                    public void onCreate(Activity activity) {
                        MyAppliaction.this.quickLoginActivity = activity;
                    }

                    @Override
                    public void onResume(Activity activity) {
                        if (activity instanceof CmccLoginActivity) {
                            View decorView = activity.getWindow().getDecorView();
                            ViewGroup contentView = decorView.findViewById(android.R.id.content);
                            ViewGroup rootView = (ViewGroup) contentView.getChildAt(0);
                            rootView.setFitsSystemWindows(false);
                        }
                    }

                    @Override
                    public void onStart(Activity activity) {
                    }

                    @Override
                    public void onPause(Activity activity) {
                    }

                    @Override
                    public void onStop(Activity activity) {
                    }

                    @Override
                    public void onDestroy(Activity activity) {
                    }
                })
                .build(this);
        quickLogin.setDebugMode(true);
        quickLogin.setUnifyUiConfig(unifyUiConfig);
        quickLogin.init(this, "f07a6b736eb641229e99ebca42d9575f");
    }

    public static void initUMSystemMassage() {
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification((Observer<CustomNotification>) message -> {
            UMSystemMassageBean umSystemMassageBean = new Gson().fromJson(message.getContent(), UMSystemMassageBean.class);
            if (umSystemMassageBean.getId() == 1008) {
                UMSystemMassageDataBean umSystemMassageDataBean = new Gson().fromJson(umSystemMassageBean.getData(), UMSystemMassageDataBean.class);
                ToastUtils.show(umSystemMassageDataBean.getTitle() + "\n\n" + umSystemMassageDataBean.getContent());
            }
        }, true);
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage((Observer<List<IMMessage>>) imMessages -> {
            if (imMessages.size() == 1) {
                LiveEventBus.<IMMessage>get("receivedGift").post(imMessages.get(0));
            }
        }, true);
    }

    private void initCramer() {
        FURenderManager.registerFURender(MyAppliaction.this, authpack.A(), new OperateCallback() {
            @Override
            public void onSuccess(int code, String msg) {
                FURenderKit.getInstance().setUseTexAsync(true);
                if (code == 200) {
                    LogUtils.i("cramer", "相机鉴权成功  ：" + msg);
                } else {
                    LogUtils.i("cramer", "相机鉴权  ：" + msg);
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                LogUtils.i("cramer", "相机鉴权失败 " + errCode + " ：" + errMsg);
            }
        });
    }

    private void initUIKit() {
        SDKOptions options = new SDKOptions();
        options.sessionReadAck = true;
        //填入APPKEY
        //正式f3cfe81e713709e6e61eb9a5dc65b51d
        options.appKey = "f31308a092ca2a9afaa474af066c1935";
        MixPushConfig mixPushConfig = new MixPushConfig();
        mixPushConfig.vivoCertificateName = "MiLiaoPushVIVO";
        mixPushConfig.oppoCertificateName = "MiLiaoPushOPPO";
        mixPushConfig.oppoAppId = "30904627";
        mixPushConfig.oppoAppKey = "e7856cb9e1bb4cf6b7b2e58e31512eaf";
        mixPushConfig.oppoAppSercet = "66b536b07460450caf706f81114849ab";
        options.mixPushConfig = mixPushConfig;
        IMKitClient.init(this, null, options);
        //初始化ChatKit-UIok
        if (NIMUtil.isMainProcess(this)) {
            com.heytap.msp.push.HeytapPushManager.init(this, true);
            ChatKitClient.init(this);
        }
    }


    public static Context getContext() {
        return context;
    }

    /**
     * 添加activity
     */
    public void addActivity(Activity activity) {
        if (!hasActivity(activity)) {
            activities.add(activity);
        }
    }

    /**
     * 判断对应activity是否存在
     */
    private boolean hasActivity(Activity activity) {

        for (int i = 0; i < activities.size(); i++) {
            Activity a = activities.get(i);
            if (a == activity) {
                return true;
            }
        }
        return false;
    }

    /**
     * 移除对应activity
     */
    public void removeActivity(Activity activity) {
        if (hasActivity(activity)) {
            activities.remove(activity);
        }
    }

    /**
     * 清除所有activity
     */
    public void clearActivity() {
        activities.clear();
    }

    /**
     * 销毁当前activity
     */
    public void destroyActivity(Activity a) {
        removeActivity(a);
        a.finish();
    }

    /**
     * 界面销毁 (1)关闭所有activity
     */
    public void finishAll() {
        if (activities.size() > 0) {
            for (Activity activity : activities) {
                if (!activity.isFinishing()) {
                    activity.finish();
                }
            }
            clearActivity();
        }
    }

    /**
     * 界面销毁 (2)退出整个程序
     */
    public void exit() {
        // wipeMapData();
        // finishAll();
        // 杀死了整个进程
        finishAll();
        System.exit(0);
    }

    /**
     * activityPageChange 页面(Activity)切换 TransmitData 传递数据 (包含基本类型数据和非基本类型数据，
     * 非基本类型数据通过传递过去的key值到transmitDataMap中去取 )
     *
     * @param a           当前Activity
     * @param c           要跳转的class
     * @param map         传输数据的键值对 没有时为null
     * @param flags       为要跳转的页面设置的flags 没有时为-1
     * @param isForResult 跳转对应页面时是调用startActivity()还是调用startActivityForResult()
     *                    默认时为false,调用startActivity(),此时下一个参数requestCode无效
     * @param requestCode 跳转页面调用startActivityForResult() 对应的请求码
     * @param b           是否关闭当前页面 为true时关闭,false时保留
     */
    public void activityPageChange(Activity a, Class<?> c,
                                   Map<String, Object> map, int flags, boolean isForResult,
                                   int requestCode, boolean b) {
        if (a == null || c == null) {
            return;
        }

        Intent intent = new Intent(a, c);
        Bundle bundle = null;

        if (map != null && map.size() > 0) {
            bundle = new Bundle();
            Set<String> keySet = map.keySet();
            for (String i : keySet) {
                Object o = map.get(i);

                if (o instanceof Integer) {
                    bundle.putInt(i, (Integer) o);
                } else if (o instanceof Double) {
                    bundle.putDouble(i, (Double) o);
                } else if (o instanceof Boolean) {
                    bundle.putBoolean(i, (Boolean) o);
                } else if (o instanceof String) {
                    bundle.putString(i, (String) o);
                } else {// 非基本数据类型
                    saveMapData(i, o);
                    bundle.putString(i, i);
                }

            }

        }

        if (flags != -1) {
            intent.setFlags(flags);
        }

        if (bundle != null) {
            intent.putExtras(bundle);
        }

        if (!isForResult) {
            a.startActivity(intent);
        } else {
            a.startActivityForResult(intent, requestCode);
        }

        if (b) {
            destroyActivity(a);
        }
    }

    /**
     * transmitDataMap存储非基本类型数据
     *
     * @param key
     * @param value
     */
    private void saveMapData(String key, Object value) {
        transmitDataMap.put(key, value);
    }

    /**
     * transmitDataMap获取非基本类型数据
     *
     * @param key
     * @return
     */
    public Object getMapData(String key) {
        return transmitDataMap.get(key);
    }

    /**
     * transmitDataMap清空数据 应当在退出app时调用
     */
    private void wipeMapData() {
        if (transmitDataMap.size() > 0) {
            transmitDataMap.clear();
        }
    }

    public static int dp2px(Context context, float dipValue) {
        try {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (dipValue * scale + 0.5f);
        } catch (Exception e) {
            return (int) dipValue;
        }
    }

    private void initExtra() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        extra.setAppVersion(BuildConfig.VERSION_NAME + "");
        String deviceId = DeviceUtils.getDeviceId();
        LogUtils.i("deviceId", deviceId);
        extra.setImei(deviceId);
        extra.setSysType("Android");
        extra.setSysVersion("Android" + Build.VERSION.RELEASE);
        extra.setPhoneType(manufacturer + model);
        extra.setPlatform("Android_appstore");
        Constants.MmkvConst.EXTRA = new Gson().toJson(extra);
    }

    public boolean judgeContainsStr(String str) {
        String regex = ".*[a-zA-Z]+.*";
        Matcher m = Pattern.compile(regex).matcher(str);
        return m.matches();
    }

    private void initBaiduLocation() {
        //定位初始化
        //定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        LocationClient.setAgreePrivacy(true);
        LocationClient locationClient;
        try {
            locationClient = new LocationClient(getApplicationContext());
        } catch (Exception e) {
            return;
        }
        //声明LocationClient类实例并配置定位参数
        LocationClientOption locationOption = new LocationClientOption();
        //注册监听函数
        locationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PERMISSION_GRANTED) {
                    String location = bdLocation.getLongitude() + "," + bdLocation.getLatitude();
                    if (judgeContainsStr(location)) {
                        extra.setLocation("");
                    } else {
                        extra.setLocation(bdLocation.getLongitude() + "," + bdLocation.getLatitude());
                    }
                    LogUtils.i("bdlocation66", bdLocation.getLongitude() + "," + bdLocation.getLatitude());
                    MyAppliaction.this.bdLocation = bdLocation;
                } else {
                    extra.setLocation("");
                }
                Constants.MmkvConst.EXTRA = new Gson().toJson(extra);
            }
        });
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        locationOption.setCoorType("bd09ll");
        //可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(2000);
        //可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);
        //可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(true);
        //可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(false);
        //可选，默认false，设置是否当卫星定位有效时按照1S1次频率输出卫星定位结果
        locationOption.setLocationNotify(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationOption.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false);
        //可选，默认false，设置是否开启卫星定位
        locationOption.setOpenGps(true);
        //可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(false);
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode();
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        locationOption.setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.setLocOption(locationOption);
        //开始定位
        locationClient.start();
    }

    public void handleSSLHandshake() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }};

            SSLContext sc = SSLContext.getInstance("TLS");
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception ignored) {
        }
    }
}
